﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;  
using Xproject.Util;
using Core.WeiXin; 
using Services.WXshopBuiness;
using Model.WXshopBuiness;
using Model.WXshopBuiness.Enum;
using Services.WeiXinProject;
using Model.WeiXin;

namespace WeiXinProject.Controllers
{
    public class WXFeedbackController : Controller
    {
        WXOrderServices m_WXOrderServices;
        PromotionServices m_PromotionServices;
        WeiXinMessageServices m_wxmessageServices;
        UserInfoServices m_UserInfoServices;
        public WXFeedbackController(WXOrderServices mWXOrderServices, PromotionServices mPromotionServices, WeiXinMessageServices mwxmessageServices, UserInfoServices mUserInfoServices)
        {
              m_WXOrderServices= mWXOrderServices;
              m_PromotionServices = mPromotionServices;
              m_wxmessageServices = mwxmessageServices;
              m_UserInfoServices = mUserInfoServices;
        }

        [HttpPost]
        [ActionName("PayResult")]
        public ActionResult Post() {
            string content = string.Empty;
            StreamReader reader = new StreamReader(Request.InputStream);
            String xmlData = reader.ReadToEnd();
            Dictionary<string, string> dic = WeiXinHelper.ReceivePostXmlData(xmlData);
            string orderId = string.Empty;
            LogHelper.WriteInfoLog("~~~~~~~~~~~~~~~~获取到微信支付结果反馈~~~~~~~~~~");
            if (dic != null)
            {
                orderId = dic["out_trade_no"];//我们自己的
                LogHelper.WriteInfoLog("~~~~~~~~~~~~~~~~pay ok  orderid :" + orderId);
            }
            else
            {
                LogHelper.WriteInfoLog("~~~~~~~ERROR ~~~~~~~~~pay  no   orderid ");
                content = ("< xml > < return_code >< ![CDATA[FAIL]] ></ return_code >< return_msg >< ![CDATA[no post data]] ></ return_msg ></ xml >");
            }

            if (!string.IsNullOrEmpty(orderId))
            {
               
                string sign = dic["sign"];
                WxPayData receiveData = new WxPayData();
                //to do 这里最好校验 sign 
               // receiveData.SetValue("",);
               // receiveData.MakeSign();
                if ("jsad78sadmASB2chenqiang" != dic["attach"]) //腾讯返回的 提交订单时的原样数据 简易校验是不是腾讯发过来的数据
                {
                    LogHelper.WriteInfoLog("~~~~~ERROR ~~~~~~~~~~~pay  error 提交订单时的原样数据 不对 提交过来的是 " + dic["attach"]);
                    content = ("<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[attach error ]]></return_msg></xml>");
                    return Content(content);
                }

                WeiXinOrder order = m_WXOrderServices.GetDBOrderById(orderId);  //得到当前的order 信息

                //校验订单金额 与腾讯支付结果金额是否一致
                int fmoney =int.Parse( dic["total_fee"]);
                int omoney = Convert.ToInt32((order.NeedToPay) * 100);
                if (fmoney != omoney)
                {
                    LogHelper.WriteInfoLog("~~~~~ERROR ~~~~~~~~~~~pay  error 提交订单时的订单价格是 " + dic["total_fee"]);
                    content = ("<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[total_fee error ]]></return_msg></xml>");
                    return Content(content);
                }
                if (order != null)
                {
                    LogHelper.WriteInfoLog("~~~~~~~~~~~~~~~~  got the order info ");
                    OrderChangeHistory history = new OrderChangeHistory();
                    history.OrderId = order.OrderID;
                    history.OrderMoney = order.OrderMoney;
                    history.StateBefore = order.OrderState;
                    history.StateAfter = (int)Enum_OrderState.PAYED;
                    history.Remarks = "微信支付完毕！订单由待支付 -->已支付" ;
                    order.OrderState =(int) Enum_OrderState.PAYED;
                    if (m_WXOrderServices.WeiXinPaySuccess(order,history))
                    {
                        Cache_UserInfoModel.Clear(order.UserID);
                        WeiXinUser user = m_UserInfoServices.GetById(order.UserID);
                        string domain = CommonHelper.GetAppSettings("Domain");
                        string url =   domain + "/Order/PayOrderDetail?orderId=" + order.OrderID;
                        m_wxmessageServices.SendOrderPaySuccessMessage(CommonHelper.GetAppSettings("MessageSender"), "", order.UserID, user.OpenId,
                           url, CommonHelper.GetAppSettings("WeiXin_APPID"), user.NickName, order.OrderName, order.OrderCode,order.NeedToPay.ToString("#0.00"));
                        //变更产品销售数目
                        m_WXOrderServices.UpdatePruductSalesCountInfo(order.ProductId);
                        //如果有使用砍价优惠活动的 要变更 优惠活动为已使用 
                        UserProductKanJia UPKJ =  m_PromotionServices.GetUserProdKJByOrder(order.OrderID);
                        if (UPKJ != null)
                        {
                            if (m_PromotionServices.UpdateUserProdKJToUsed(UPKJ))
                            {
                                LogHelper.WriteInfoLog("订单使用了砍价优惠，优惠信息已被标志 使用 订单是：" + order.OrderID);
                            }
                            else
                            {
                                LogHelper.WriteInfoLog("~~~~~ERROR ~~~~~~~~~~~订单使用了砍价优惠，但更新砍价优惠出错  订单是：" + order.OrderID);
                            }
                        }
                        content = ("<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                    }
                }
            }
            return Content(content);
        }

    }
}